# -*-  conding: utf-8 -*-
# Author: czh
# Datetime : 2022/5/9 13:12
import time

import tushare as ts
from pprint import pprint
import pandas as pd
from datetime import date, timedelta, datetime
import isopenday

# # 获取今天的日期，并转化成相应格式
import xlwt as xlwt

day = date.today()
today = format(day.strftime('%Y%m%d'))
# 初始化pro接口  陈
# pro = ts.pro_api('cf37ab059637ac7f5d628bdd046a9bcb2c1e34c2fa7546e6b8659225')

# 初始化pro接口  康
pro = ts.pro_api('3b52e2e8f4f8de54e3d662f06b62ef3373da8593d8428776cb2af432')


def get_next_date(ts_code, start_date, close):
    """ 根据日期获取未来五个交易日的增幅 ts_code:股票代码600313.SH ； start_date：开始时间"""
    pct_chg_list = ""
    zhangdie = ""
    next_zhangfu = "没取到值"
    open_day_list = isopenday.open_day_list
    index = open_day_list.index(start_date)
    five_day_list = open_day_list[index + 1:index + 4]
    # 拉取数据
    time.sleep(0.1)
    # 拉取数据
    pct_chg = pro.daily(
        **{"ts_code": ts_code, "trade_date": five_day_list[0], "start_date": "", "end_date": "",
           "offset": "",
           "limit": ""
           },
        fields=["ts_code", "trade_date", "open", "high", "low", "close", "pre_close", "change", "pct_chg", "vol",
                "amount"
                ])

    # for idx, data in pct_chg.iterrows():
    try:
        # pct_chg_list.append(data[8])
        pct_chg_list = pct_chg.iloc[0, 8]
        next_zhangfu = round((pct_chg.iloc[0, 3] - close) / close, 3) * 100
        if pct_chg_list > 0:
            zhangdie = "涨"
        else:
            zhangdie = "跌"

    except:
        print("遇到一个错误：", name)
    # pct_chg_list.reverse()
    return pct_chg_list, zhangdie, next_zhangfu


def jisuan(open, high, low, close, trade_date, ts_code, pct, pre_close, name):
    """ 计算下影线 / 实体 大于2.5"""
    shiti = abs(open - close)
    xiaying = min(open, close) - low
    shangying = high - max(open, close)
    chazhi = high - low
    jieguo5 = round(chazhi / open, 2)
    try:

        if xiaying == 0.0 or pct < 0 or shangying > xiaying / 2 or "ST" in name:
            # print("跳过：", shiti, xiaying)
            pass
        else:
            if shiti == 0:
                pct_chg_list = get_next_date(ts_code, trade_date, close)
                # print(name, trade_date, "当日0涨幅：", pct, pct_chg_list)
                return name, ts_code, trade_date, pct, pct_chg_list
            else:
                jieguo = round(xiaying / shiti, 2)
                jieguo2 = round(shangying / shiti, 2)
                jieguo3 = round(chazhi / open, 2)
                # jieguo4 = round(shangying / xiaying, 2)
                # print(jieguo3)
                # if jieguo > 2 and jieguo2 < 1:
                if 0.09 >= jieguo3 > 0.07 and (0.1 > jieguo or jieguo > 2.5) and jieguo2 < 1:
                    pct_chg_list = get_next_date(ts_code, trade_date, close)
                    # print(name, trade_date, "当日涨幅:", pct, pct_chg_list)
                    return name, ts_code, trade_date, pct, pct_chg_list
    except:
        print("有个计算错了：", name, ts_code)


if __name__ == '__main__':

    """ 获取每只股票的当天数据 """
    # 拉取数据:
    """
    01ts_code股票代码 02trade_date交易日期 03open开盘价 04high最高价 05low最低价 06close收盘价 07pre_close昨收价 08change涨跌额 09pct_chg涨跌幅 10vol成交量 11amount成交额"""
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
    name_list = []
    trade_date_list = []
    symbol_list = []
    today_pct_list = []
    five_pct_list = []
    five_pct_zhangdie = []
    next_zhangfu = []
    content = []
    f_csv = pd.read_csv("shishi.csv", skiprows=100, nrows=100)
    for index, data1 in f_csv.iterrows():
        #  获取股票代码，名称
        name = data1[2]
        symbol = data1[1][2:] + "." + data1[1][:2].upper()
        print("开始执行第{0}支股票:{1}".format(index, name))

        df = pro.daily(**{
            "ts_code": symbol, "trade_date": "", "start_date": 20210509, "end_date": 20220509, "offset": "",
            "limit": ""
        }, fields=["ts_code", "trade_date", "open", "high", "low", "close", "pre_close", "change", "pct_chg", "vol",
                   "amount"
                   ])

        for idx, data in df.iterrows():
            # 提取数据
            open = data[2]
            high = data[3]
            low = data[4]
            close = data[5]
            trade_date = data[1]
            ts_code = data[0]
            pct = data[8]
            pre_close = data[6]
            save_tul = jisuan(open, high, low, close, trade_date, ts_code, pct, pre_close, name)
            if save_tul is not None:
                name_list.append(save_tul[0])
                symbol_list.append(save_tul[1])
                trade_date_list.append(save_tul[2])
                today_pct_list.append(save_tul[3])
                five_pct_list.append(save_tul[4][0])
                five_pct_zhangdie.append(save_tul[4][1])
                next_zhangfu.append(save_tul[4][2])
            else:
                pass
        if index > 100:
            break
    #   保存至Excel
    pd.DataFrame({"股票名称": name_list, "股票代码": symbol_list, "交易日期": trade_date_list, "当天的涨幅": today_pct_list,
                  "下一日的涨幅": five_pct_list, "下一日最高点涨幅": next_zhangfu, "下一日涨还是跌": five_pct_zhangdie}).to_excel(
        "百支股票数据7到9.xlsx")
    print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
